$(function () {
    // 表单提交
    var $submit = $('#submit'), $error = $('.error');

    $('[name="img-code"]').click(function () {
        $(this).attr('src', $(this).attr('src') + '?rna=' + Math.random());
    });
    function refresh() {
        $('.img-code').attr('src', '/api/admin/code/captcha-image?rna=' + Math.random());
    }

    $("#user-form").submit(function (_form) {
        var fields = 'userName|password|imgCode';
        $submit.button('loading');
        setTimeout(function () {
            if ($submit.attr('disabled') == 'disabled') {
                $submit.button('reset');
                fnSuccess('请勿多次重复提交~')
            }
        }, 3000);
        var form = {};
        var form_ = [];
        fields.split('|').map(function (item) {
            form[item] = $(_form.target).find('[name=' + item + ']').val();
            if (item == 'userName') {
                form_.push('phone=' + $(_form.target).find('[name=' + item + ']').val());
            } else {
                form_.push(item + '=' + $(_form.target).find('[name=' + item + ']').val());
            }
        });

        var url = '/user/login';
        // md5();
        if (form.password) {
            form.password = md5(form.password.trim())
        }
        $.post(url, form, function (res) {
            if (res.code == 200) {
                if (res.data && res.data.roles && !res.data.roles.length) {
                    refresh();
                    $error.html("用户未指派角色，不能登录!");
                } else {
                    //
                    ;
                    LS.json('MANAGER_CURRENT', res.data);
                    window.location.href = './index.html?id=' + res.data.id;
                }
            } else {
                refresh();
                $error.html(res.error || res.msg);
            }
            $submit.button('reset');
        });


        return false;
    });
});